﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LiteDB;
using NLog;
using NovelFetch.Models;

namespace NovelFetch
{
    public enum EditFlag
    {
        View = 0,
        Add = 1,
        Del = 2,
        Modify = 3
    }
    public partial class RuleForm : Form
    {
        private static NLog.Logger _logger = LogManager.GetCurrentClassLogger();
        private EditFlag EditStatus;
        private List<BookRule> _bookRules;
        private List<KeyValuePair<string, string>> _ruleNameSiteList;
        private List<BookRule> _insertRules;
        private List<BookRule> _modifyRules;
        public RuleForm()
        {
            InitializeComponent();
            _ruleNameSiteList = new List<KeyValuePair<string, string>>();
            _insertRules = new List<BookRule>();
            _modifyRules = new List<BookRule>();
        }

        private void RuleForm_Load(object sender, EventArgs e)
        {
            EditStatus = EditFlag.View;
            using (var db = new LiteDatabase(@"novel.db"))
            {
                var rules = db.GetCollection<BookRule>();
                rules.EnsureIndex(w => w.RuleName);
                _bookRules = rules.FindAll().ToList();
                foreach (var m in _bookRules)
                {
                    _ruleNameSiteList.Add(new KeyValuePair<string, string>(m.RuleName, m.SiteUrl));
                    
                }
                cbRuleName.DisplayMember = "Key";
                cbRuleName.ValueMember = "Value";
                cbRuleName.DataSource = _ruleNameSiteList;
                //cbRuleName.SelectedIndex = -1;
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            EditStatus = EditFlag.Add;
            gbModify.Visible = false;
            gbSave.Visible = true;
            cbSiteEncode.SelectedIndex = 0;
            cbRuleName.SelectedIndex = -1;
            tbSiteUrl.Clear();
            tbSiteName.Clear();
            tbTitleRule.Clear();
            tbCatalogRule.Clear();
            tbContentRule.Clear();
            nudHeaderLine.Value = nudFooterLine.Value = 0;
            nudHeaderLine.Enabled = true;
            nudFooterLine.Enabled = true;
            cbSiteEncode.Enabled = true;
            cbRuleName.Enabled = true;
            tbSiteUrl.Enabled = true;
            tbSiteName.Enabled = true;
            tbTitleRule.Enabled = true;
            tbCatalogRule.Enabled = true;
            tbContentRule.Enabled = true;
            

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            EditStatus = EditFlag.Del;
            if (MessageBox.Show("确认删除该网站规则?", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
            {
                var ruleName = cbRuleName.SelectedItem?.ToString();
                using (var db = new LiteDatabase(@"novel.db"))
                {
                    var bookRule = db.GetCollection<BookRule>();
                    if (bookRule.Delete(w => w.RuleName == ruleName) > 0)
                    {
                        MessageBox.Show($"成功删除{ruleName}站点规则");
                        cbRuleName.Items.Remove(cbRuleName.SelectedItem);
                    }

                }
            }
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            EditStatus = EditFlag.Modify;
            gbModify.Visible = false;
            gbSave.Visible = true;
            cbSiteEncode.Enabled = true;
            cbRuleName.Enabled = false;
            tbSiteUrl.Enabled = true;
            tbSiteName.Enabled = true;
            tbTitleRule.Enabled = true;
            tbCatalogRule.Enabled = true;
            tbContentRule.Enabled = true;
            
            nudHeaderLine.Enabled = true;
            nudFooterLine.Enabled = true;
        }



        private void btnSave_Click(object sender, EventArgs e)
        {

            try
            {
                var encode = cbSiteEncode.SelectedItem?.ToString();
                var ruleName = cbRuleName.Text;
                var siteUrl = tbSiteUrl.Text;
                var siteName = tbSiteName.Text;
                var titleRule = tbTitleRule.Text;
                var catalogRule = tbCatalogRule.Text;
                var contentRule = tbContentRule.Text;
                if (string.IsNullOrEmpty(encode))
                {
                    MessageBox.Show("站点编码不能为空");
                    return;
                }

                if (string.IsNullOrEmpty(ruleName))
                {
                    MessageBox.Show("站点名称不能为空");
                    return;
                }

                if (string.IsNullOrEmpty(siteUrl))
                {
                    MessageBox.Show("站点地址不能为空");
                    return;
                }
                if (!siteUrl.StartsWith("http://") || siteUrl.StartsWith("https://"))
                {
                    siteUrl = "http://" + siteUrl;
                }
                if (string.IsNullOrEmpty(titleRule))
                {
                    MessageBox.Show("标题规则不能为空");
                    return;
                }

                if (string.IsNullOrEmpty(catalogRule))
                {
                    MessageBox.Show("目录规则不能为空");
                    return;
                }

                if (string.IsNullOrEmpty(contentRule))
                {
                    MessageBox.Show("内容规则不能为空");
                    return;
                }
                
                using (var db = new LiteDatabase(@"novel.db"))
                {
                    var bookRule = db.GetCollection<BookRule>();
                    var configModel = new BookRule
                    {
                        RuleName = ruleName,
                        SiteEncode = encode,
                        Remarks = siteName,
                        SiteUrl = siteUrl,
                        TitleRule = titleRule,
                        CatalogRule = catalogRule,
                        ContentRule = contentRule
                    };
                    var obj = bookRule.FindOne(w => w.RuleName == ruleName);
                    
                    //bookRule.EnsureIndex(w => w.RuleName);
                    if (EditStatus == EditFlag.Add)
                    {
                        if(obj != null)
                        {
                            MessageBox.Show("站点名不能重复", "错误");                            
                        }
                        else
                        {
                            bookRule.Insert(configModel);
                            var kv = new KeyValuePair<string, string>(ruleName, siteUrl);
                            _ruleNameSiteList.Add(kv);
                            cbRuleName.Items.Add(kv);
                        }
                       
                    }
                    if (EditStatus == EditFlag.Modify)
                    {
                        if (obj != null)
                        {
                            configModel.Id = obj.Id;
                        }
                        bookRule.Update(configModel);
                        var idx = _ruleNameSiteList.FindIndex(w => w.Key == ruleName);
                        _ruleNameSiteList.RemoveAt(idx);
                        _ruleNameSiteList.Add(new KeyValuePair<string, string>(ruleName, siteUrl));
                    }
                    _bookRules = bookRule.FindAll().ToList();
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
            finally
            {
                EditStatus = EditFlag.View;
                cbSiteEncode.Enabled = false;
                cbRuleName.Enabled = true;
                tbSiteUrl.Enabled = false;
                tbSiteName.Enabled = false;
                tbTitleRule.Enabled = false;
                tbCatalogRule.Enabled = false;
                tbContentRule.Enabled = false;
                gbModify.Visible = true;
                gbSave.Visible = false;
                nudHeaderLine.Enabled = false;
                nudFooterLine.Enabled = false;
            }
            
        }

        private void btnNoSave_Click(object sender, EventArgs e)
        {
            EditStatus = EditFlag.View;
            gbModify.Visible = false;
            gbSave.Visible = true;
            cbSiteEncode.SelectedIndex = 0;
            cbRuleName.SelectedIndex = -1;
            tbSiteUrl.Clear();
            tbSiteName.Clear();
            tbTitleRule.Clear();
            tbCatalogRule.Clear();
            tbContentRule.Clear();
            cbSiteEncode.Enabled = false;
            cbRuleName.Enabled = true;
            tbSiteUrl.Enabled = false;
            tbSiteName.Enabled = false;
            tbTitleRule.Enabled = false;
            tbCatalogRule.Enabled = false;
            tbContentRule.Enabled = false;
            gbModify.Visible = true;
            gbSave.Visible = false;
            nudHeaderLine.Enabled = false;
            nudFooterLine.Enabled = false;
        }


        private void RuleSelectChange()
        {
            if (_bookRules != null)
            {
                var selVal = cbRuleName.Text;
                if (!string.IsNullOrEmpty(selVal))
                {
                    var item = _bookRules.Find(w => w.RuleName == selVal);
                    if (item != null)
                    {
                        cbSiteEncode.SelectedItem = item.SiteEncode;

                        tbSiteUrl.Text = item.SiteUrl;
                        tbSiteName.Text = item.Remarks;
                        tbTitleRule.Text = item.TitleRule;
                        tbCatalogRule.Text = item.CatalogRule;
                        tbContentRule.Text = item.ContentRule;
                        nudHeaderLine.Value = item.HeaderSkipLine;
                        nudFooterLine.Value = item.FooterSkipLine;
                       
                    }
                }
            }
        }

        private void cbRuleName_SelectedIndexChanged(object sender, EventArgs e)
        {
            RuleSelectChange();
        }
    }
}
